#include <jni.h>
#include <stdio.h>
#include "gtkwire_lock.h"

/* pointer to vmachine */
static JavaVM *jvm = NULL;

/* Java object that gets callbacks, app singleton "this" */
static jobject glade_app = 0;

/* Java monitor object */
static jobject gtklock;

/* Captures references to jvm, app singleton instance. */
void
init_java_gtk_lock (JNIEnv *env, jobject caller_glade_app, jobject jlock)
{
	/* Initialize the jvm global variable */
	(*env)->GetJavaVM (env, &jvm);

	/* Get global ref from caller glade app */
	glade_app = (*env)->NewGlobalRef (env, caller_glade_app);

	/* Get global ref from monitor obj */
	gtklock = (*env)->NewGlobalRef (env, caller_glade_app);
}

/* Get java lock */
void
get_java_gtk_lock ()
{
	/* Get env.*/
	JNIEnv* env;
	(*jvm)->GetEnv(jvm, (void **) &env, JNI_VERSION_1_4);
	if (env == NULL) 
	{
		printf("Failed to get env in get_java_gtk_lock ().");
		/* to do: something */
	}

	/* Get java monitor lock */
	if ((*env)->MonitorEnter(env, gtklock) != JNI_OK) 
	{
		printf( "Failed MonitorEnter in get_java_gtk_lock ().");
		/* to do: something */
	}
}

/* Release java lock */
void
release_java_gtk_lock ()
{
	/* Get env.*/
	JNIEnv* env;
	(*jvm)->GetEnv(jvm, (void **) &env, JNI_VERSION_1_4);
	if (env == NULL) 
	{
		printf("Failed to get env in release_java_gtk_lock ().");
		/* to do: something */
	}

	/* Release java monitor */
	if ((*env)->MonitorExit(env, gtklock) != JNI_OK) 
	{
		printf( "Failed MonitorExit in release_java_gtk_lock ().");
		/* to do: something */
	}
}
